package com.easysoft.commons.interceptor;

import com.easysoft.commons.utils.StringUtils;
import com.easysoft.commons.utils.UUIDUtils;
import com.easysoft.commons.utils.WebConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {
    private static Logger logger = LoggerFactory
            .getLogger(WebSocketHandshakeInterceptor.class);

    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) serverHttpRequest;
        HttpSession session = servletRequest.getServletRequest().getSession(false);
        map.put(WebConstants.SESSION_USER_ID, session.getAttribute(WebConstants.SESSION_USER_ID) == null ? UUIDUtils.getUUID() : (String) session.getAttribute(WebConstants.SESSION_USER_ID));
        map.put(WebConstants.IS_LOGIN, session.getAttribute(WebConstants.SESSION_USER_ID) != null);
        map.put("ip", serverHttpRequest.getRemoteAddress().toString());
        String customer = servletRequest.getServletRequest().getParameter("customer");
        if (StringUtils.isNotNullAndBlank(customer)) {
            map.put("customer", customer);
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
    }
}
